import os, re
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from utils import common
from manager.models import *

from django.conf import settings
# 验证器
from manager.formModel.categoryForm import *
from manager.formModel.articleForm import *

# 栏目管理页面
def category(request):
    # 获取所有栏目信息
    items = Category.objects.all().values('id', 'cate_name', 'picture', 'count')
    # 获取后台菜单
    menu = settings.MENU
    # 获取信息传递到模板中
    data = {
        "user": request.session.get('user'),
        "menu": menu,
        'items': items,
        'count': items.count()
    }
    return render(request, 'backstage/category/category.html', data)


# 添加栏目
def category_add(request):
    # 表单验证器   实例化 CategoryForm类返回一个对象
    categoryForm = CategoryForm(request.POST)
    if request.is_ajax():
        # 验证通过时返回的是True
        if categoryForm.is_valid():
            # 根据验证器的字段属性 获取验证成功的数据，返回一个字典
            cate = categoryForm.cleaned_data
            cate['picture'] = request.FILES['picture']
            """
            等同于
            添加栏目信息
            cate ={
                "cate_name": request.POST.get('cate_name'),
                "pic": request.FILES['picture'],
                "describles": request.POST.get('describles'),
                "seo_title": request.POST.get('seo_title'),
                "seo_keyword": request.POST.get('seo_keyword'),
                "seo_description": request.POST.get('seo_description')

            }
            """
            Category.objects.create(**cate)
            return JsonResponse({'msg': '添加成功！', 'code': 0, 'data': []})

        return JsonResponse({'msg': '添加失败！', 'code': 1, 'data': []})

    return render(request, 'backstage/category/category_add.html', {'categoryForm': categoryForm})


def category_edit(request):
    # get 请求,返回的都是 html
    id = request.GET.get('id')
    print(id)
    # id不能为空
    if not id:
        html = common.msg('要修改的栏目id不能为空！')
        return HttpResponse(html)

    # 表单验证器   实例化 CategoryForm类返回一个对象
    categoryForm = CategoryForm(request.POST)
    if request.is_ajax():
        if categoryForm.is_valid():
            # 获取验证成功并且要修改的内容
            cate = categoryForm.cleaned_data
            # 追加要修改的图片对象
            if request.FILES.get('picture', None):
                cate['picture'] = request.FILES['picture']
                # 可以删除老的图片
                # # 获取图片的绝对物理路径
                # picture = os.path.join(settings.BASE_DIR, request.POST.get('oldpic'))
                # # 删除物理图片
                # if cate.pic and os.path.isfile(picture): os.remove(picture)

            else:
                del cate['picture']

            # 更新当前栏目信息
            # Category(id=id, **cate) 创建category模型对象
            # update_fields要求更新那些字段
            Category(id=id, **cate).save(update_fields=cate.keys())
            return JsonResponse({'msg': '操作成功！', 'code': 0, 'data': []})
        return JsonResponse({'msg': '操作失败！', 'code': 1, 'data': []})

    try:
        # 获取指定id的栏目信息
        data = Category.objects.get(id=id)  # 如果get查询不到数据时 会抛出异常
    except Exception as e:
        html = common.msg('修改异常！')
        return HttpResponse(html)

    return render(request, 'backstage/category/category_edit.html', {"data": data, "categoryForm": categoryForm})

def category_del(request):
    """
    栏目删除
    :param request:
    :return:
    """
    id = request.GET.get('id')
    # id不能为空
    if not id:
        return JsonResponse({'msg': '请选择要操作的数据！', 'code': 1, 'data': []})

    # 删除指定数据
    cate = Category.objects.get(id=id)
    # 获取图片的绝对物理路径
    picture = os.path.join(settings.BASE_DIR, str(cate.picture))
    # 删除物理图片
    if cate.picture and os.path.isfile(picture): os.remove(picture)
    cate.delete()
    return JsonResponse({'msg': '删除成功！', 'code': 0, 'data': []})